//
//  SettingViewController.m
//  yilutongxing
//
//  Created by T&J on 2018/1/8.
//  Copyright © 2018年 YZE. All rights reserved.
//

#import "SettingViewController.h"
#import "UserDefaultsTools.h"
#import "AppDelegate.h"
#import "TimeTools.h"

@interface SettingViewController ()
@property (strong, nonatomic) IBOutlet UISwitch *toggle;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"设置";
    
    NSDictionary *setting = [UserDefaultsTools getUserDefaultsForKey:SETTING];
    if (!setting || !setting[MEDICINE_ALERT_TOOGLE]) {
        [self.toggle setOn:YES];
    }
    else {
        NSNumber *alertFlag = setting[MEDICINE_ALERT_TOOGLE];
        BOOL isAlert = [alertFlag boolValue];
        [self.toggle setOn:isAlert];
    }
    
    [self.toggle addTarget:self action:@selector(onToggle:) forControlEvents:UIControlEventValueChanged];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

#pragma mark - 开关响应
- (void)onToggle:(id)sender{
    //debugLog(@"[SHENMI]开关服药闹钟");
    UISwitch *toggle = (UISwitch*)sender;
    [UserDefaultsTools saveUserDefaultsObject:@{MEDICINE_ALERT_TOOGLE:[NSNumber numberWithBool:[toggle isOn]]} forKey:SETTING];
    if (![toggle isOn]) {
        //清除已设置的闹钟
        [self removeAllMedicineAlert];
    }
}

#pragma mark - 业务逻辑
- (void)removeAllMedicineAlert{
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [TimeTools removeAllMedicineAlertInDB:[app sharedEventStore]];
}

@end
